'use strict';

const Service = require('egg').Service;
const Route = require('../model/route');

class RouteService extends Service {
  // 将数据库模型转换为DTO
  toDTO(route) {
    if (!route) return null;
    
    return {
      id: route.id,
      userId: route.user_id,
      travelPlanId: route.travel_plan_id,
      dailyPlanId: route.daily_plan_id,
      title: route.title,
      routesData: JSON.parse(route.routes_data),
      createdAt: route.created_at,
      updatedAt: route.updated_at
    };
  }

  // 获取用户的所有路线
  async list(userId) {
    try {
      const routes = await Route.findAll({
        where: { user_id: userId },
        order: [['created_at', 'DESC']]
      });
      
      return {
        success: true,
        data: routes.map(route => this.toDTO(route))
      };
    } catch (error) {
      return { success: false, message: '获取路线列表失败', error: error.message };
    }
  }

  // 根据ID获取路线
  async getById(id, userId) {
    try {
      const route = await Route.findOne({
        where: { id, user_id: userId }
      });
      
      if (!route) {
        return { success: false, message: '路线不存在或无权访问' };
      }
      
      return {
        success: true,
        data: this.toDTO(route)
      };
    } catch (error) {
      return { success: false, message: '获取路线详情失败', error: error.message };
    }
  }

  // 创建路线
  async create(userId, payload) {
    try {
      // 验证必要字段
      if (!payload.title || !payload.routesData) {
        return { success: false, message: '标题和路线数据不能为空' };
      }
      
      const route = await Route.create({
        user_id: userId,
        travel_plan_id: payload.travelPlanId || null,
        daily_plan_id: payload.dailyPlanId || null,
        title: payload.title,
        routes_data: JSON.stringify(payload.routesData)
      });
      
      return {
        success: true,
        message: '路线创建成功',
        data: this.toDTO(route)
      };
    } catch (error) {
      return { success: false, message: '创建路线失败', error: error.message };
    }
  }

  // 更新路线
  async update(id, userId, payload) {
    try {
      const route = await Route.findOne({
        where: { id, user_id: userId }
      });
      
      if (!route) {
        return { success: false, message: '路线不存在或无权修改' };
      }
      
      // 更新字段
      const updateData = {};
      if (payload.title) updateData.title = payload.title;
      if (payload.routesData) updateData.routes_data = JSON.stringify(payload.routesData);
      if (payload.travelPlanId !== undefined) updateData.travel_plan_id = payload.travelPlanId;
      if (payload.dailyPlanId !== undefined) updateData.daily_plan_id = payload.dailyPlanId;
      
      await Route.update(updateData, {
        where: { id, user_id: userId }
      });
      
      const updatedRoute = await Route.findByPk(id);
      
      return {
        success: true,
        message: '路线更新成功',
        data: this.toDTO(updatedRoute)
      };
    } catch (error) {
      return { success: false, message: '更新路线失败', error: error.message };
    }
  }

  // 删除路线
  async destroy(id, userId) {
    try {
      const route = await Route.findOne({
        where: { id, user_id: userId }
      });
      
      if (!route) {
        return { success: false, message: '路线不存在或无权删除' };
      }
      
      await Route.destroy({
        where: { id, user_id: userId }
      });
      
      return {
        success: true,
        message: '路线删除成功'
      };
    } catch (error) {
      return { success: false, message: '删除路线失败', error: error.message };
    }
  }

  // 获取旅行计划下的所有路线
  async getByPlanId(planId, userId) {
    try {
      const routes = await Route.findAll({
        where: { 
          travel_plan_id: planId,
          user_id: userId
        },
        order: [['created_at', 'DESC']]
      });
      
      return {
        success: true,
        data: routes.map(route => this.toDTO(route))
      };
    } catch (error) {
      return { success: false, message: '获取计划路线失败', error: error.message };
    }
  }
}

module.exports = RouteService;